<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <table>
        <tr>
            <td>
                书籍: <input type="text" name="bookName">
            </td>
        </tr>
        <tr>
            <td>
                分类: <input type="text" name="bookSort">
            </td>
        </tr>
        <tr>
            <td>
                作者: <input type="text" name="bookAuthor">
            </td>
        </tr>
        <tr>
            <td>
                <button onclick="onUpdate()">提交</button>
                <a href="./index.html">取消</a>
            </td>
        </tr>



    </table>
    <script src="./js/jquery-3.6.1.min.js"></script>
    <script>
        // 获取id 
        let id = location.search.substring(4);

        if (id) {
            //修改时：绑定数据
            $.get(`http://localhost:3000/v1/books/${id}`, (obj) => {
                $('[name=bookName]').val(obj.data.name);
                $('[name=bookSort]').val(obj.data.sort);
                $('[name=bookAuthor]').val(obj.data.author);
            });
        }



        function onUpdate() {
            let bookName = $('[name=bookName]').val();
            let bookSort = $('[name=bookSort]').val();
            let bookAuthor = $('[name=bookAuthor]').val();
            let obj = {
                name: bookName,
                sort: bookSort,
                author: bookAuthor
            }

            //修改：put
            if (id) {
                $.ajax({
                    url: `http://localhost:3000/v1/books/${id}`,
                    type: 'put',
                    data: obj,
                    success: (obj) => {
                        if (obj.code == '200') {
                            alert(obj.msg);
                            location.href = './index.html';
                        }
                    }
                });
                // 新增
            } else {
                $.ajax({
                    url: `http://localhost:3000/v1/books`,
                    type: 'post',
                    data: obj,
                    success: (obj) => {
                        if (obj.code == '200') {
                            alert(obj.msg);
                            location.href = './index.html';
                        }
                    }
                });
            }

        }

    </script>
</body>

</html>